package com.example.shopping_web_back.controller;

import com.example.shopping_web_back.pojo.Goods;
import com.example.shopping_web_back.pojo.Result;
import com.example.shopping_web_back.pojo.Business;
import com.example.shopping_web_back.service.BusinessService;
import com.example.shopping_web_back.utils.JwtUtil;
import com.example.shopping_web_back.utils.ThreadLocalUtil;
import jakarta.validation.constraints.Pattern;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

//本文件主要是为了解决与用户有关的操作
@RestController
@RequestMapping("/Business")
@Validated
public class BusinessController {

    @Autowired
    private BusinessService businessService;

    private static final String CURRENT_PATH = System.getProperty("user.dir");
    private static final String IMAGE_DIR = CURRENT_PATH + "/uploads/image/business/";

    //注册商家
    @PostMapping("/register")
    public Result register(@Pattern(regexp = "^\\S{2,10}$") String business_name,@Pattern(regexp = "^\\S{6,20}$") String password) {
        //查询商家是否存在，有则被占用了，无法注册
        Business Business = businessService.findByBusinessName(business_name);
        if (Business == null) {
            //如果不存在，则注册
            businessService.register(business_name,password);
            return Result.success();
        }else {
            //如果占用了
            return Result.error("用户名已被占用");
        }
    }

    //商家登录
    @PostMapping("/login")
    public Result<String> login(@Pattern(regexp = "^\\S{2,10}$") String business_name,@Pattern(regexp = "^\\S{6,20}$") String password) {
        //根据商家名查询商家
        Business loginBusiness = businessService.findByBusinessName(business_name);
        //判断商家是否存在
        if(loginBusiness == null) {
            return Result.error("用户名错误");
        }
        //判断密码是否正确
        if(password.equals(loginBusiness.getPassword())) {
            //登录成功
            Map<String,Object> claims = new HashMap<>();
            claims.put("id",loginBusiness.getId());
            claims.put("Business_name",loginBusiness.getName());
            String token = JwtUtil.genToken(claims);
            return Result.success(token);
        }
        return Result.error("密码错误");
    }

    //得到商家信息
    @GetMapping("/businessInfo")
    public Result<Business> businessInfo(@RequestHeader(name = "Customer")String token) {
        //根据用户名查询商家
        Map<String, Object> map = ThreadLocalUtil.get();
        if(map == null)
        {
            return Result.success(null);
        }
        String businessName = (String)map.get("Business_name");
        Business business = businessService.findByBusinessName(businessName);
        return Result.success(business);
    }

    //更新商家信息
    @PostMapping("/update")
    public Result update(@RequestBody @Validated Business business) {
        businessService.update(business);
        return Result.success();
    }

    //上传商家头像
    @PostMapping("/uploadImage")
    public Result upload(@RequestHeader(name = "Customer") String token, @RequestParam("file")MultipartFile Image) throws IOException {
        Map<String, String> map = ThreadLocalUtil.get();
        String businessName = (String)map.get("Business_name");
        //获取当前时间
        String timestamp = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
        //获取文件扩展名
        String originalFileName = Image.getOriginalFilename();
        String fileExtension = "";
        if(originalFileName != null && originalFileName.lastIndexOf('.') > 0) {
            fileExtension = originalFileName.substring(originalFileName.lastIndexOf('.'));
        }
        File dir = new File(IMAGE_DIR);
        String fileName = businessName + "_" +timestamp + fileExtension;
        Path filePath = Paths.get(IMAGE_DIR + fileName);
        Files.copy(Image.getInputStream(), filePath);
        return Result.success("http://8.138.173.30:8080/image/business/" + fileName);
    }

    //更新商家头像
    @PostMapping("/updateImage")
    public Result updateImage(@RequestHeader(name = "Customer") String token,@RequestBody Map<String, String> avatar) throws ParseException, IOException {
        String avatarUrl = avatar.get("file");
        String fileName = avatarUrl.substring(avatarUrl.lastIndexOf('/') + 1);
        // 提取文件名前缀和时间戳
        String[] parts = fileName.split("_", 2); // 分割为两部分，前缀和后面的时间戳
        String prefix = parts[0]; // 获取前缀
        String timestampString = parts[1].split("\\.")[0]; // 获取时间戳字符串
        long avatarTimestamp = new SimpleDateFormat("yyyyMMddHHmmss").parse(timestampString).getTime();
        //先得到用户名
        Map<String, Object> map = ThreadLocalUtil.get();
        String businessName = (String)map.get("Business_name");

        File dir = new File(IMAGE_DIR);
        File[] files = dir.listFiles((directory, name) -> name.startsWith(prefix + "_") && !name.equals(fileName)); // 只匹配相同前缀的文件

        if (files != null) {
            for (File file : files) {
                String fileBaseName = file.getName();
                String[] fileParts = fileBaseName.split("_", 2); // 分割为两部分，前缀和时间戳
                String filePrefix = fileParts[0]; // 获取当前文件的前缀

                if (filePrefix.equals(prefix)) { // 确保前缀相同
                    String fileTimestampString = fileParts[1].split("\\.")[0]; // 获取时间戳字符串
                    long fileTimestamp = new SimpleDateFormat("yyyyMMddHHmmss").parse(fileTimestampString).getTime();

                    if (fileTimestamp < avatarTimestamp) {
                        Files.delete(file.toPath());
                    }
                }
            }
        }

        businessService.updateImage(avatarUrl);
        return Result.success(avatarUrl);
    }

    //更新商家密码
    @PostMapping("/updatePassword")
    public Result updatePassword(@RequestBody Map<String, String> params) {
        //校验参数
        String oldPwd = params.get("old_pwd");
        String newPwd = params.get("new_pwd");
        String rePwd = params.get("re_pwd");

        if(!StringUtils.hasLength(oldPwd) || !StringUtils.hasLength(newPwd) || !StringUtils.hasLength(rePwd)) {
            return Result.error("缺少参数");
        }
        //校验原密码是否正确
        Map<String, Object> map = ThreadLocalUtil.get();
        String businessName = (String) map.get("Business_name");
        Business loginBusiness = businessService.findByBusinessName(businessName);
        if(!loginBusiness.getPassword().equals(oldPwd)) {
            return Result.error("原密码填写不正确");
        }
        //校验两次密码填写是否正确
        if(!rePwd.equals(newPwd)) {
            return Result.error("两次填写的密码不一样");
        }
        //调用Service层完成密码更新
        businessService.updatePassword(newPwd);
        return Result.success();
    }

    //查询该商家上架的全部商品
    @GetMapping("/getAllGoods")
    public Result<List<Goods>> searchAllGoods(@RequestHeader(name = "Customer")String token) {
        //根据用户名查询商家
        Map<String, Object> map = ThreadLocalUtil.get();
        String businessName = (String)map.get("Business_name");
        List<Goods> allGoods = businessService.searchAllGoods(businessName);
        return Result.success(allGoods);
    }
}
